package com.cloud.lawcase.api.provider;

import org.apache.commons.lang.StringUtils;

import com.cloud.lawcase.api.bean.LawCauseInterfaceSearchCriteria;

public class InterfaceLawCausePageProvider {

	public String searhCausePageInfo(LawCauseInterfaceSearchCriteria criteria) {
		StringBuilder sqlBuilder = new StringBuilder(
				"select a1.law_id,a1.law_code,a1.law_title,a1.cause_id,a1.cause_code,a1.cause_name,a2.item_id, a2.item_name from (select t1.law_id, t1.law_code, t1.law_title, t2.cause_id, t2.cause_code, t2.cause_name ,t2.item_id  from tc_dic_law t1, tc_dic_law_cause t2 where t1.law_id = t2.law_id and t1.sx_id = 1 ");
		//区划
		if (!StringUtils.isEmpty(criteria.getRegionCodes())) {
			sqlBuilder.append(" and t1.law_region_id in (");
			boolean b = false;
			String[] rCodes = criteria.getRegionCodes().split(",");
			for (String regionCode : rCodes) {
				if(b)sqlBuilder.append(",");
				sqlBuilder.append("'").append(regionCode).append("'");
				b = true;
			}
			sqlBuilder.append(") ");
		}
		//职能部门
		if(!StringUtils.isEmpty(criteria.getUnitFuncTypes())){
			sqlBuilder.append(" and exists (select * from tc_rel_punish_unit_func t4 where t4.cause_id = t2.cause_id and t4.unit_func_type_id in("+ criteria.getUnitFuncTypes() +"))");
		}
		//适用程序类别
		if(criteria.getBizId() > 0){
			sqlBuilder.append(" and exists (select * from tc_law_rel_cause_biz t3 where t3.cause_id = t2.cause_id and t3.biz_id = "+criteria.getBizId()+")");
		}
		//案件处罚类型
		if(criteria.getExcuteTypeId() > 0){
			sqlBuilder.append(" and t2.excute_type_id = "+ criteria.getExcuteTypeId());
		}
		//案由关键字
		if(!StringUtils.isEmpty(criteria.getCauseName())){
			sqlBuilder.append(" and t2.cause_name like '%"+criteria.getCauseName()+"%'");
		}
		//法规信息
		if(null != criteria.getLawId() && criteria.getLawId() > 0){
			sqlBuilder.append(" and t1.law_id = "+ criteria.getLawId() +"");
		}else{
			//法规名称关键字
			if(!StringUtils.isEmpty(criteria.getLawTitle())){
				sqlBuilder.append(" and t1.law_title like '%"+criteria.getLawTitle().trim()+"%'");
			}
		}
		//条目信息
		if(null != criteria.getItemId() && criteria.getItemId() > 0){
			sqlBuilder.append(" and (t2.item_id = "+ criteria.getItemId() +" or t2.cause_id in (select cause_id from tc_law_rel_cause_law_item where item_id = "+criteria.getItemId() +")) ");
		}
		//违责关键字
		if(!StringUtils.isEmpty(criteria.getWzItem())){
			sqlBuilder.append(" and exists (select * from tc_law_rel_cause_law_item a1, tc_dic_law_item a2 where a1.item_id = a2.item_id and a1.item_type_id = 1 and a2.item_content like '%"+ criteria.getWzItem().trim() +"%' and t2.cause_id = a1.cause_id)");
		}
		
		sqlBuilder.append(" ) a1 left join tc_dic_law_item a2 on a1.law_id = a2.law_id and a1.item_id = a2.item_id");
		return sqlBuilder.toString();
	}
}
